<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId'.$cfgPack])
  || (isset($_SESSION['s_userType'.$cfgPack]) && isset($cfgFileNames['deliveryChalan'][$_SESSION['s_userType'.$cfgPack]]) 
      && $cfgFileNames['deliveryChalan'][$_SESSION['s_userType'.$cfgPack]] == 0))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{
	
  $subCategoryName         = array();
  $techName                = array();
  $partyId                 = "";
  $supplierId              = "";
  $itemId                  = "";
  $itemName                = "";
  $categoryName            = "";
  $categoryId              = "";
  $address                 = "";
  $challanType             = "";
  $delivaryDate            = "";
  $firstName               = "";
  $deliveryChallanDetailId = "";
  $deliveryChallanMasterId = 0;
  $quantity                = "";
  $useChallanMasterId      = 0;
  $srnoSelected            = 0;
  // edit assign variable Start:::::
  $isEdit                  = 0;
  $detailArr               = array();
  $detailCount             = 0;
  $masterIdSelected        = 0;
  $partyIdSelected         = 0;
  $supplierIdSelected      = 0;
  $srNo                    = 0;
  $delivaryDateSelected    = 0;
  $addressSelected         = "";
  $technicianIdSelected   = 0;
  $callFunction            = "";
  // edit assign variable End:::::
  $lastInserId             = isset($_REQUEST['lastInserId']) ? $_REQUEST['lastInserId'] : 0;
  $challanShort            = isset($_REQUEST['challanShort']) ? $_REQUEST['challanShort'] : "";
  switch($challanShort)
  {
    case "DCN":
      $pageHeader = "Delivery Challan/Note(DCN)";
      break;
    case "GIN":
      $pageHeader = "Goods Inward Note(GIN)";
      break;
    case "GRN":
      $pageHeader = "Goods Return Note(GRN)";
      break;
    case "GRJ":
      $pageHeader = "Goods Rejection(GRJ)";
      break;
    default:
      $pageHeader = "Delivery Challan";
      break;
  }
  // To know the delivery challan type Start///

  $srnoQuery = "SELECT MAX(srNo) AS maxSrNO
                  FROM deliverychallanmaster
                 WHERE 1 = 1 ";
  if(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'DCN')
  {
    $srnoQuery .= " AND challanType = 'Delivery Challan/Note'";
  }
  elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GIN')
  {
  	$srnoQuery .= " AND challanType = 'Goods Inward Note'";
  }
  elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GRN')
  {
  	$srnoQuery .= " AND challanType = 'Goods Return Note'";
  }
  elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GRJ')
  {
  	$srnoQuery .= " AND challanType = 'Goods Rejection'";
  }          
           
  $srnoQueryResult = mysql_query($srnoQuery);
  if($srnoRow = mysql_fetch_array($srnoQueryResult))
  {
    $srnoSelected   = $srnoRow['maxSrNO'] + 1;
  }
  
  if(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'DCN')
  {
    $challanType =  'Delivery Challan/Note';
  }
  elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GIN')
  {
  	$challanType =  "Goods Inward Note";
  }
  elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GRN')
  {
  	$challanType =  "Goods Return Note";
  }
  elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GRJ')
  {
  	$challanType =  "Goods Rejection";
  }
  if(isset($_REQUEST['challanFull']))
  	$challanType =  $_REQUEST['challanFull'];
  // To know the delivery challan type End///       
  
  if(isset($_REQUEST['deliveryChallanMasterId']) && $_REQUEST['deliveryChallanMasterId'] > 0 && $_SESSION['s_userType'.$cfgPack] == 'superAdmin')
  {
    $isEdit = 1;
    if(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GIN')
    {
      $selectDelivery = "SELECT deliverychallanmaster.deliveryChallanMasterId,deliverychallanmaster.supplierId,deliverychallanmaster.srNo,
                                deliverychallandetail.deliveryChallanDetailId,deliverychallanmaster.delivaryDate,deliverychallanmaster.address,deliverychallanmaster.technicianId,deliverychallanmaster.userId,
                                deliverychallandetail.subCategoryId,deliverychallandetail.itemId,deliverychallandetail.discription,deliverychallandetail.quantity,
                                supplier.companyName,item.itemName,subcategory.subCategoryName
                           FROM deliverychallanmaster
                           JOIN deliverychallandetail ON deliverychallandetail.deliveryChallanMasterId = deliverychallanmaster.deliveryChallanMasterId
                           JOIN supplier ON supplier.supplierId = deliverychallanmaster.supplierId
                           JOIN subcategory ON subcategory.subCategoryId = deliverychallandetail.subCategoryId
                           JOIN item ON item.itemId  = deliverychallandetail.itemId
                          WHERE deliverychallanmaster.deliveryChallanMasterId=".$_REQUEST['deliveryChallanMasterId'];
    }
    else
    {
       $selectDelivery = "SELECT deliverychallanmaster.deliveryChallanMasterId,deliverychallanmaster.partyId,deliverychallanmaster.srNo,
                                 deliverychallanmaster.delivaryDate,deliverychallanmaster.address,deliverychallanmaster.technicianId,deliverychallanmaster.userId,
                                 deliverychallandetail.deliveryChallanDetailId,deliverychallandetail.subCategoryId,deliverychallandetail.itemId,deliverychallandetail.discription,deliverychallandetail.quantity,
                                 party.companyName,item.itemName,subcategory.subCategoryName
                            FROM deliverychallanmaster
                            JOIN deliverychallandetail ON deliverychallandetail.deliveryChallanMasterId = deliverychallanmaster.deliveryChallanMasterId
                            JOIN party ON party.partyId = deliverychallanmaster.partyId
                            JOIN subcategory ON subcategory.subCategoryId = deliverychallandetail.subCategoryId
                            JOIN item ON item.itemId  = deliverychallandetail.itemId
                           WHERE deliverychallanmaster.deliveryChallanMasterId=".$_REQUEST['deliveryChallanMasterId'];
    }
    $deliveryRes = mysql_query($selectDelivery);
    while ($deliveryRow = mysql_fetch_array($deliveryRes))
    {
    	$callFunction .= "subCategoryComboEdit(".$deliveryRow['subCategoryId'].",".($detailCount+1).",".$deliveryRow['itemId'].");";
      $masterIdSelected      = $deliveryRow['deliveryChallanMasterId'];
      if(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GIN')
      {
        $supplierIdSelected      = $deliveryRow['supplierId'];
      }
      else
      {
        $partyIdSelected         = $deliveryRow['partyId'];
      }
      $srNo                 = $deliveryRow['srNo'];
      $delivaryDateSelected = $deliveryRow['delivaryDate'];
      $addressSelected      = $deliveryRow['address'];
      $technicianIdSelected = $deliveryRow['technicianId'];
      $detailArr[$detailCount]['deliveryChallanDetailId'] = $deliveryRow['deliveryChallanDetailId'];
      $detailArr[$detailCount]['subCategoryId'] = $deliveryRow['subCategoryId'];
      $detailArr[$detailCount]['itemId']        = $deliveryRow['itemId'];
      $detailArr[$detailCount]['discription']   = $deliveryRow['discription'];
      $detailArr[$detailCount]['quantity']      = $deliveryRow['quantity'];
      $detailCount++;
    }
  }
  
  if(isset($_POST['delivaryDateDay']) || isset($_POST['printBtn']))
  {
    $curDate = new DateTime();
    $curDate->setTimezone($cfgTimeZone);
    $timeset = $curDate->format('H:i:s');
    $delivaryDate = $_POST['delivaryDateYear']."-".$_POST['delivaryDateMonth']."-".$_POST['delivaryDateDay']." ".$timeset;
    $technicianId = isset($_POST['technicianId']) ? $_POST['technicianId'] : 0;
    if(isset($_POST['partyId']))
      $party = $_POST['partyId'];
    else
      $party = 0;
      
    if(isset($_POST['supplierId']))
      $supplier = $_POST['supplierId'];
    else
      $supplier = 0;
    if(isset($_POST['deliveryChallanMasterId']) && $_POST['deliveryChallanMasterId'] > 0)
    {
     $deleteDetail = "DELETE FROM deliverychallandetail WHERE deliveryChallanMasterId=".$_POST['deliveryChallanMasterId'];
     $deleteDetailRow = mysql_query($deleteDetail);
     $updateDeliveryChallan = "UPDATE deliverychallanmaster
                                  SET partyId = ".$party.",
                                      supplierId = ".$supplier.",
                                      delivaryDate = '".$delivaryDate."',
                                      address = '".$_POST['address']."',technicianId = ".$technicianId.",
                                      userId = ".$_SESSION['s_activeUserId'.$cfgPack].",
                                      challanType = '".$challanType."' 
                                WHERE deliveryChallanMasterId=".$_REQUEST['deliveryChallanMasterId'];
      $updateDeliveryChallanRes = mysql_query($updateDeliveryChallan);
      if(!$updateDeliveryChallanRes)
      {
      	echo "Failed to Update".mysql_error();
      }
      else
      {
      	header("Location:deliveryChalanList.php");
      }
      $deliveryChallanMasterId = $_REQUEST['deliveryChallanMasterId'];                           
    }
    else
    {
    	
      $srnoQuery = "SELECT (MAX(srNo) + 1) AS maxSrNO
                      FROM deliverychallanmaster
                     WHERE 1 = 1 ";
      if(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'DCN')
      {
        $srnoQuery .= " AND challanType = 'Delivery Challan/Note'";
      }
      elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GIN')
      {
      	$srnoQuery .= " AND challanType = 'Goods Inward Note'";
      }
      elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GRN')
      {
      	$srnoQuery .= " AND challanType = 'Goods Return Note'";
      }
      elseif(isset($_REQUEST['challanShort']) && $_REQUEST['challanShort'] == 'GRJ')
      {
      	$srnoQuery .= " AND challanType = 'Goods Rejection'";
      }          
               
      $srnoQueryResult = mysql_query($srnoQuery);
      if($srnoRow = mysql_fetch_array($srnoQueryResult))
      {
        $srNoInsert   = $srnoRow['maxSrNO'];
      }
  
      $insertDeliveryChallan = "INSERT INTO deliverychallanmaster (partyId,supplierId,srNo,delivaryDate,address,technicianId,userId,challanType)
                                     VALUES(".$party.",".$supplier.",".$srNoInsert.",'".$delivaryDate."',
                                            '".nl2br(addslashes($_POST['address']))."',".$technicianId.",".$_SESSION['s_activeUserId'.$cfgPack].",'".$challanType."')";
      $insertDeliveryChallanResult = mysql_query($insertDeliveryChallan);
      $deliveryChallanMasterId = mysql_insert_id();
    }
    $loopCount = 0;
    while($loopCount < count($_POST['subCategoryId']))
    {
      $deliveryChallanDetailId = isset($_POST['deliveryChallanDetailId'][$loopCount]) && ($_POST['deliveryChallanDetailId'][$loopCount] != '') ? $_POST['deliveryChallanDetailId'][$loopCount] : 0;
      $itemId         = ($_POST['itemId'][$loopCount] != '') ? $_POST['itemId'][$loopCount] : 0;
      $subCategoryId  = ($_POST['subCategoryId'][$loopCount] != '') ? $_POST['subCategoryId'][$loopCount] : 0;
      $quantity       = ($_POST['netQuantityUsed'][$loopCount] != '') ? $_POST['netQuantityUsed'][$loopCount] : 0;
      $discription    = ($_POST['descriptionOfMaterial'][$loopCount] != '') ? $_POST['descriptionOfMaterial'][$loopCount] : "";
      if(isset($_POST['remarks']))
        $remarks        = ($_POST['remarks'][$loopCount] != '') ? $_POST['remarks'][$loopCount] : "";
      else
        $remarks = "";
      
      if($_POST['itemId'][$loopCount] != "" ||
         $_POST['categoryId'][$loopCount] != "" || $_POST['netQuantityUsed'][$loopCount] != "" )
      {

///////////// Item current stock update : Start
			  if($_REQUEST['challanShort'] == 'DCN' || $_REQUEST['challanShort'] == 'GRJ')
			    $appendQuery = " currentStock = currentStock - ".$quantity;
			  else
			    $appendQuery = " currentStock = currentStock + ".$quantity;
			    
			  $updateItemQuery = "UPDATE item
		                           SET ".$appendQuery."
		                         WHERE itemId = ".$itemId;
			  $updateItemQueryResult = mysql_query($updateItemQuery);
			  if(!$updateItemQueryResult)
			    die("Record Not Updated : ". mysql_error());
///////////// Item current stock update : End
        $insertDeliveryChallanDetail = "INSERT INTO deliverychallandetail (deliveryChallanMasterId,discription,subCategoryId,itemId,quantity,remarks)
                                             VALUES(".$deliveryChallanMasterId.",'".nl2br(addslashes($discription))."',".$subCategoryId.",
                                             ".$itemId.",".$quantity.",'".$remarks."')";
        $insertDeliveryChallanDetailResult = mysql_query($insertDeliveryChallanDetail);
        $lastDeliveryChallanInsertId = mysql_insert_id();
        if($deliveryChallanDetailId != 0 && $isEdit == 1)
        {
          $updateGoodsReturn = "UPDATE goodsreturn
                                   SET deliveryChallanDetailId = ".$lastDeliveryChallanInsertId." 
                                 WHERE deliveryChallanDetailId=".$deliveryChallanDetailId;
          $updateRes = mysql_query($updateGoodsReturn);
        }
        if(!$insertDeliveryChallanDetailResult)
          die("Insert Query Not Inserted : ".mysql_error());
      }
      $loopCount++;
    }
    if($isEdit == 0)
    {
      if(!$insertDeliveryChallanResult)
      {
	      die("Insert Query Error : ". mysql_error());
	    }
	    else
	    {
	      if(isset($_POST['printBtn']))
	      {
	        if($party != 0)
	          header("Location:deliveryChallanDetail.php?print=1&partyRequest=1&deliveryChallanMasterId=".$deliveryChallanMasterId);
	        else
	          header("Location:deliveryChallanDetail.php?print=1&supplierRequest=1&deliveryChallanMasterId=".$deliveryChallanMasterId);
	      }
	      else
	      {
	        header("Location:deliveryChalanList.php");
	        exit;
	      }
	    }
    }
    else
    {
      if(!$updateDeliveryChallanRes)
      {
	      die("Update Query Error : ". mysql_error());
	    }
	    else
	    {
        //header("location:deliveryChalanList.php");
      }
    }
  }   
 ///// Select Party : Start
  $selectParty = "SELECT partyId,companyName
                    FROM party 
                ORDER BY companyName";
  $selectPartyResult = mysql_query($selectParty);
  $b = 0;
  while($partyRow = mysql_fetch_array($selectPartyResult))
  {
    $partyId[$b]   = $partyRow['partyId'];
    $firstName[$b] = substr_replace($partyRow['companyName'],'...',40);
    $b++;
  }
  ///// Select Party : Ends
 ///// Select Supplier : Start
  $selectSupplier = "SELECT supplierId,companyName
                       FROM supplier
                   ORDER BY companyName";
  $selectSupplierResult = mysql_query($selectSupplier);
  $c = 0;
  while($supplierRow = mysql_fetch_array($selectSupplierResult))
  {
    $supplierId[$c]  = $supplierRow['supplierId'];
    $companyName[$c] = $supplierRow['companyName'];
    $c++;
  }
  ///// Select Supplier : Ends
  ///// Select Category : Start
  $selectCategoryQuery = "SELECT subCategoryId,subCategoryName
	                          FROM subcategory
	                      ORDER BY subCategoryName";
	$selectCategoryQueryRes = mysql_query($selectCategoryQuery);
	$j = 0;
	while($categoryRow = mysql_fetch_array($selectCategoryQueryRes))
	{
	  if($j == 0 || (isset($_REQUEST['subCategoryId']) && $_REQUEST['subCategoryId'] == $categoryRow['subCategoryId']))
	    $categorySelected = $categoryRow['subCategoryId'];
	
	  $subCategoryName['subCategoryId'][$j]   = $categoryRow['subCategoryId'];
	  $subCategoryName['subCategoryName'][$j] = $categoryRow['subCategoryName'];
	  $j++;
	}
  ///// Select Category : Ends
  ///// Select Technician : Start
  $selectTech = "SELECT technicianId,firstName
	                          FROM technician
	                         WHERE userType = 'None'
	                      ORDER BY firstName";
	$selectTechRes = mysql_query($selectTech);
	$t = 0;
	while($tectRow = mysql_fetch_array($selectTechRes))
	{
	  if($t == 0 || (isset($_REQUEST['technicianId']) && $_REQUEST['technicianId'] == $categoryRow['technicianId']))
	    $techSelected = $categoryRow['technicianId'];
	
	  $techName['technicianId'][$t]   = $tectRow['technicianId'];
	  $techName['firstName'][$t] = $tectRow['firstName'];
	  $t++;
	}
  ///// Select Technician : Ends
  
  include("./bottom.php");
  $smarty->assign("pageHeader",$pageHeader);
  $smarty->assign("challanShort",$challanShort);
  $smarty->assign("srnoSelected",$srnoSelected);
  $smarty->assign("subCategoryName",$subCategoryName);
  $smarty->assign("techName",$techName);
  $smarty->assign("partyId",$partyId);
  $smarty->assign("itemId",$itemId);
  $smarty->assign("categoryId",$categoryId);
  $smarty->assign("quantity",$quantity);
  $smarty->assign("itemName",$itemName);
  $smarty->assign("categoryName",$categoryName);
  $smarty->assign("address",$address);
  $smarty->assign("challanType",$challanType);
  $smarty->assign("deliveryChallanMasterId",$deliveryChallanMasterId);
  $smarty->assign("delivaryDate",$delivaryDate);
  $smarty->assign("firstName",$firstName);
  $smarty->assign("supplierId",$supplierId);
  $smarty->assign("companyName",$companyName);
  $smarty->assign("deliveryChallanDetailId",$deliveryChallanDetailId);
  $smarty->assign("lastInserId",$lastInserId);
  // edit assign variable Start:::::
  $smarty->assign("isEdit",$isEdit);
  $smarty->assign("detailArr",$detailArr);
  $smarty->assign("masterIdSelected",$masterIdSelected);
  $smarty->assign("partyIdSelected",$partyIdSelected);
  $smarty->assign("supplierIdSelected",$supplierIdSelected);
  $smarty->assign("srNo",$srNo);
  $smarty->assign("delivaryDateSelected",$delivaryDateSelected);
  $smarty->assign("addressSelected",$addressSelected);
  $smarty->assign("technicianIdSelected",$technicianIdSelected);
  $smarty->assign("callFunction",$callFunction);
  // edit assign variable End:::::
  $smarty->display("deliveryChalan.tpl");
}
?>